<template>
  <div style="padding: 15px">
    <vxe-toolbar
      id="warehouseLocationId"
      :custom="{ storage: true }"
      export
      :refresh="{ query: findList }"
    >
      <template v-slot:buttons>
        <el-button @click="findList">查询</el-button>
        <el-button @click="funcCreateBatchTask">下发</el-button>
        <el-button @click="funcAdd">新增</el-button>
        <el-button @click="funcPrint" :disabled="!printFlag"
          >打印移位单</el-button
        >
      </template>
    </vxe-toolbar>
    <vxe-table
      ref="xTable"
      border
      resizable
      stripe
      highlight-current-row
      :align="allAlign"
      show-footer
      highlight-hover-row
      row-id="id"
      class="mytable-footer"
      height="700"
      :loading="loading"
      :export-config='{type:"csv"}'
      :data="tableData"
      :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }"
      sort-config.remote
      @sort-change="sortList"
      auto-resize
      :seq-config="{startIndex: listQuery.pageNum * listQuery.pageSize - listQuery.pageSize}"
    >
      <vxe-table-column type="seq" width="60"></vxe-table-column>
      <vxe-table-column type="checkbox" width="60"></vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="status"
          title="状态"
          min-width="140"
          sortable
          show-header-overflow
          show-overflow
          :formatter="formatterStatus"
        />
        <template v-slot:header="{ column }">
          <el-select
            v-model="listQuery.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option value="0" label="新增" />
            <!--<el-option value="1" label="待审核" />
            <el-option value="2" label="审核通过" />
            <el-option value="3" label="驳回" />-->
            <el-option value="11" label="待移位" />
            <el-option value="12" label="移位中" />
            <el-option value="13" label="移位完成" />
            <el-option value="4" label="作废" />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="issue" title="是否下发" min-width="150" sortable show-header-overflow show-overflow :formatter="formatterIssue"/>
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.issue" placeholder="请选择" clearable>
            <el-option
              v-for="item in issueList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>


      <vxe-table-column>
        <vxe-table-column
          field="code"
          title="移位单号"
          min-width="200"
          sortable
          show-header-overflow
          show-overflow
        />
        <template v-slot:header="{ column }">
          <el-input
            v-model="listQuery.code"
            placeholder="请输入移位单号"
            clearable
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="warehouseName"
          title="仓库"
          min-width="200"
          sortable
        />
        <template v-slot:header="{ column }">
          <el-select
            v-model="listQuery.warehouseCode"
            placeholder="请选择仓库 "
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="item in warehouseData"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="totalQuantity"
          title="总数量"
          min-width="180"
          sortable
        />
        <template v-slot:header="{ column }">
          <!-- <el-input v-model="listQuery.totalQuantity" placeholder="请输入总数量" clearable /> -->
          <el-row type="flex" align="middle" style="color: #dcdfe6">
            <el-input
              v-model="listQuery.totalQuantityFloor"
              placeholder="下限"
              type='number' style="width:45%;"
              ref="quantity"
            />
            &nbsp;-&nbsp;
            <el-input
              v-model="listQuery.totalQuantityCeiling"
              placeholder="上限"
              type='number' style="width:45%;"
            />
          </el-row>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="createdName"
          title="创建人"
          min-width="150"
          sortable
        />
        <template v-slot:header="{ column }">
          <el-input
            v-model="listQuery.createdName"
            placeholder="请输入创建人"
            clearable
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="gmtCreated"
          title="创建时间"
          min-width="400"
          sortable
          show-header-overflow
          show-overflow
        />
        <template v-slot:header="{ column }">
          <el-date-picker
            v-model="gmtCreatedRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width:100%"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="(value) => changeDate(value, 'gmtCreated')"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="modifiedName"
          title="修改人"
          min-width="150"
          sortable
        />
        <template v-slot:header="{ column }">
          <el-input
            v-model="listQuery.modifiedName"
            placeholder="请输入修改人"
            clearable
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="gmtModified"
          title="修改时间"
          min-width="400"
          sortable
        />
        <template v-slot:header="{ column }">
          <el-date-picker
            v-model="gmtModifiedRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width:100%"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="(value) => changeDate(value, 'gmtModified')"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column title="操作" fixed="right" min-width="200">
        <template slot-scope="scope">
          <template v-if="scope.row.status == 0">
            <el-tooltip
              effect="dark"
              content="修改"
              placement="top"
            >
              <vxe-button type="text" @click="funcEdit(scope.row.code)">
                <i class="el-icon-edit" />
              </vxe-button>
            </el-tooltip>
            <el-tooltip
              effect="dark"
              content="作废"
              placement="top"
            >
              <vxe-button type="text" @click="funcBlank(scope.row.code)">
                <i class="el-icon-delete" />
              </vxe-button>
            </el-tooltip>
          </template>

          <template v-if="scope.row.status == 11">
            <el-tooltip
              effect="dark"
              content="移位"
              placement="top"
            >
              <vxe-button type="text" @click="funcMove(scope.row.code)">
                <i class="el-icon-check" />
              </vxe-button>
            </el-tooltip>
          </template>

          <template v-if="scope.row.status == 12">
            <el-tooltip
              effect="dark"
              content="移位"
              placement="top"
            >
              <vxe-button type="text" @click="funcMove(scope.row.code)">
                <i class="el-icon-check" />
              </vxe-button>
            </el-tooltip>
          </template>

          <template v-if="scope.row.status == 3">
            <el-tooltip
              effect="dark"
              content="修改"
              placement="top"
            >
              <vxe-button type="text" @click="funcEdit(scope.row.code)">
                <i class="el-icon-edit" />
              </vxe-button>
            </el-tooltip>
            <el-tooltip
              effect="dark"
              content="作废"
              placement="top"
            >
              <vxe-button type="text" @click="funcBlank(scope.row.code)">
                <i class="el-icon-delete" />
              </vxe-button>
            </el-tooltip>
          </template>
          <el-tooltip  effect="dark" content="下发" placement="top" v-if="scope.row.issue == '0' && scope.row.status == '11' ">
            <vxe-button type="text" @click="funcCreateTask(scope.row.code)">
              <i class="el-icon-s-promotion" />
            </vxe-button>
          </el-tooltip>

          <el-tooltip  effect="dark" content="查看" placement="top">
            <vxe-button type="text" @click="funcDetail(scope.row.code)">
              <i class="el-icon-document" />
            </vxe-button>
          </el-tooltip>
        </template>
      </vxe-table-column>
    </vxe-table>
    <vxe-pager
      :loading="loading"
      :current-page.sync="listQuery.pageNum"
      :page-size.sync="listQuery.pageSize"
      :total="listQuery.total"
      :layouts="[
        'PrevJump',
        'PrevPage',
        'Number',
        'NextPage',
        'NextJump',
        'Sizes',
        'FullJump',
        'Total',
      ]"
      @page-change="handlePageChange"
    />
    <vxe-modal
      v-model="modelPrintFlag"
      title="打印"
      width="900"
      height="800"
      resize
    >
      <compPrint ref="printRef" @fatherPrintMethod="fatherPrint" />
    </vxe-modal>
  </div>
</template>
<script>
import Vue from "vue";
import VXETable from "vxe-table";
import "xe-utils";
import "vxe-table/lib/index.css";
import XEUtils from "xe-utils";
import VXEUtils from "vxe-utils";
Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ["cookie"] });
import { moveList, moveBlank } from "@/api/store";
import compPrint from "./components/print.vue";
import { getWarehouse} from "@/api/basicInfo";
import { createTask, createBatchTask } from '@/api/store'

export default {
  name: "移位管理",
  components: {
    compPrint,
  },
  data() {
    return {
      message: "",
      // 日期选项
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      loading: false,
      // 表格初始化状态判断
      initTableFlag: false,
      allAlign: "center",
      tableData: [],
      modelAuditFlag: false,
      modelAddFlag: false,
      modelEditFlag: false,
      modelDetailFlag: false,
      modelPrintFlag: false, //打印开关
      gmtCreatedRange:"",
      gmtModifiedRange:"",
      copy: false,
            issueList: [
        {code: '0', name:'否'},
        {code: '1', name:'是'},
      ],

      warehouseData: [],
      listQuery: {
        total: 0, //总数
        createdBy: "", //创建人
        modifiedBy: "", //修改人
        code: "", //移位单号 ,
        remarks: "", //备注 ,
          status: "", //状态 ,
          totalQuantity: "", //总数量 ,
          warehouseCode: "", //仓库
          pageNum: 1,
          pageSize: 10,
          sortField: "",
          sortType: "",
          totalQuantityFloor: "", //总数量上下限
          totalQuantityCeiling: "",
          issue: "", //是否下发 ,
      },
    };
  },
  created() {
    this.findList();
    this.$eventBus.$on("refreshList", () => {
      this.findList()
    })
  },
  computed: {
    printFlag() {
      // 使用状态判断表格是否已初始化，避免xTable为null，这里在数据查询后再将状态设为true
      if (this.initTableFlag) {
        let records = this.$refs.xTable.getCheckboxRecords();
        if (records.length > 0) {
          return true;
        }
      }
      return false;
    },
  },

  methods: {
    // 单个下发
    funcCreateTask(code){
      let params = {
        taskType: 'MOVE',
        sourceCode: code
      }
      createTask(params).then((response)=>{
        this.$message({ dangerouslyUseHTMLString: true,message: response.msg, type: 'success'})
        this.findList()
      })
    },

    // 批量下发
    funcCreateBatchTask(){
      let selectRecords = this.$refs.xTable.getCheckboxRecords()
      if(selectRecords.length == 0){
        this.$message.error("请选择要下发的单据!");
        return
      }
      let codes = []
      selectRecords.forEach( i => {
        codes.push(i.code)
      })

      let params = {
        taskType: 'MOVE',
        sourceCodes: codes
      }

      createBatchTask(params).then((response)=>{
        this.$message({ dangerouslyUseHTMLString: true,message: response.msg, type: 'success'})
        this.findList()
      })
    },

    // 仓库查询
    getWarehouse() {
      return getWarehouse().then((response) => {
        this.warehouseData = response.data;
      });
    },
    changeDate(value, prefix) {
      if (value) {
        this.listQuery[`${prefix}Start`] = value[0] + " 00:00:00";
        this.listQuery[`${prefix}End`] = value[1] + " 23:59:59";
      } else {
        this.listQuery[`${prefix}Start`] = "";
        this.listQuery[`${prefix}End`] = "";
      }
    },
      formatterIssue({cellValue}){
          if(cellValue == '0'){
              return '否'
          }else if(cellValue == '1'){
              return  '是'
          }
          return cellValue
      },
    // 翻译状态
    formatterStatus({ cellValue }) {
      if (cellValue === "0") {
        return "新增";
      } else if (cellValue === "1") {
        return "待审核";
      } else if (cellValue === "2") {
        return "审核通过";
      } else if (cellValue === "3") {
        return "驳回";
      } else if (cellValue === "4") {
        return "作废";
      } else if(cellValue === "11"){
          return "待移位";
      }else if(cellValue === "12"){
          return "移位中";
      } else if(cellValue === "13"){
          return "移位完成";
      }
    },
    // 打印组件的父方法
    fatherPrint() {
      this.modelPrintFlag = false;
      this.findList();
    },
    //打印
    funcPrint() {
      let nowDate = new Date();
      let year = nowDate.getFullYear();
      let month = nowDate.getMonth() + 1;
      let date = nowDate.getDate();
      let hh =new Date(nowDate).getHours() < 10? "0" + new Date(nowDate).getHours(): new Date(nowDate).getHours();
      let mm =new Date(nowDate).getMinutes() < 10? "0" + new Date(nowDate).getMinutes(): new Date(nowDate).getMinutes();
      let ss =new Date(nowDate).getSeconds() < 10? "0" + new Date(nowDate).getSeconds(): new Date(nowDate).getSeconds();

      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (date >= 0 && date <= 9) {
        date = "0" + date;
      }
      let systemDate = year + '-' + month + '-' + date +" "+ hh + ":" + mm + ':' + ss ;
      this.$refs.printRef.date = systemDate;
      let selectRecords = this.$refs.xTable.getCheckboxRecords();
      let arr = [];
      selectRecords.forEach((i) => {
        arr.push(i.code);
      });
      this.$refs.printRef.getInfo(arr);
      this.modelPrintFlag = true;
    },

    //获取列表
    findList() {
      this.getWarehouse();
      if (
        // 总数量拦截
        this.listQuery.totalQuantityCeiling &&
        Number(this.listQuery.totalQuantityFloor) >
          Number(this.listQuery.totalQuantityCeiling)
      ) {
        this.$message.error("查询总数量下限不得大于上限！");
        this.$refs.quantity.focus();
        return;
      }
      this.loading = true;
      return moveList(this.listQuery).then((response) => {
        this.tableData = response.data.records;
        this.listQuery.total = response.data.total;
        this.loading = false;
        this.initTableFlag = true;
      });
    },
    // 排序
    sortList({ column, property, order }) {
      if (order) {
        this.listQuery.sortField = property;
        this.listQuery.sortType = order;
      } else {
        this.listQuery.sortField = "";
      }
      this.findList();
    },
    // 添加方法
    funcAdd() {
      this.$router.push({
        path: "moveAdd",
        // query: { code: code},
      });
    },
    // 修改方法
    funcEdit(code) {
      this.$router.push({
        path: "moveEdit",
        query: { code: code },
      });
    },
    // 详情方法
    funcDetail(code) {
      this.$router.push({
        path: "moveDetail",
        query: { code: code },
      });
    },

    // 审核方法
    funcAudit(code) {
      this.$refs.auditRef.getInfo(code);
      this.modelAuditFlag = true;
    },
    //移位
    funcMove(code){
      this.$router.push({
        path: "moveAudit",
        query: { code: code },
      });

    },
    // 作废方法
    funcBlank(code) {
      this.$confirm("确认作废吗？")
        .then((_) => {
          moveBlank({ code }).then((response) => {
            if (response.status == "0") {
              this.findList();
            }
          });
        })
        .catch((_) => {});
    },

    // 增加组件的父方法
    fatherAdd() {
      this.modelAddFlag = false;
      this.findList();
    },
    // 编辑组件的父方法
    fatherEdit() {
      this.modelEditFlag = false;
      this.findList();
    },
    // 审核组件的父方法
    fatherAudit() {
      this.modelAuditFlag = false;
      this.findList();
    },
    // 公共取消
    fatherCancel(modelFlag) {
      switch (modelFlag) {
        case "audit":
          this.modelAuditFlag = false;
          break;
        case "edit":
          this.modelEditFlag = false;
          break;
        default:
      }
    },
    // 分页handle
    handlePageChange({ currentPage, pageSize }) {
      this.listQuery.pageNum = currentPage;
      this.listQuery.pageSize = pageSize;
      this.findList();
    },
    // 设置底部合计
    footerMethod({ columns, data }) {
      return [
        columns.map((column, columnIndex) => {
          if (columnIndex === 0) {
            return "合计";
          }
          if (["pageviews", "forecast"].includes(column.property)) {
            return XEUtils.sum(data, column.property);
          }
          return null;
        }),
      ];
    },
  },
  destroyed() {
    this.$eventBus.$off('refreshList')
  },
};
</script>

<style>
.vxe-table .vxe-body--column:not(.col--ellipsis),
.vxe-table .vxe-footer--column:not(.col--ellipsis),
.vxe-table .vxe-header--column:not(.col--ellipsis) {
  padding: 6px 0;
}
.vxe-toolbar {
  padding: 0 0 10px 0;
}
</style>
